$NG.AllReady(function (page, { useValuesChange, useDataIndexChange, useUpdateRows, useUpdateRow, useBeforeClick }) {
    const mstform = $NG.getCmpApi("p_form_car_rental_m")
    const dgrid = $NG.getCmpApi("p_form_car_rental_d")
    if (page.oType == "add") {
        console.log($NG.getUser());
        const user = $NG.getUser()
        mstform.getItem("exchangerate").setValue(1); //汇率默认为1
        // 币种默认为人民币
        mstform.getItem("phid_fcur").setValue({
            value: 1,
            label: "人民币",
        });
        $NG.updateState((updater) => {
            updater.data.p_form_car_rental_m.setProps({
                bill_name: "租车申请",
                u_ywlx: "车辆运营费",
                u_app_org: {
                    label: user.orgName,
                    value: user.orgID
                },
                creator: {
                    label: user.userName,
                    value: user.userID
                }
            })
        })//8570000000000352  8570000000000382


        $NG.execServer("getEpmInfoByUserID", { phid: user.userID }, function (res) {
            console.log(`用户信息查询`, res);
            if (res.count != 0) {
                const _data = JSON.parse(res.data)[0].extendObjects
                console.log(_data);
                $NG.updateState((updater) => {
                    updater.data.p_form_car_rental_m.setProps({
                        u_app_org: {
                            label: user.orgName,
                            value: user.orgID
                        },
                        // creator:{
                        //     label:user.fu_phid,
                        //     value:user.hem_name
                        // },
                        phid_dept: {
                            label: _data.dept_name,
                            value: _data.dept_phid
                        }
                    })
                })
            }
        })

    }
    useValuesChange(({ args }) => {
        getProjectInfo()
    }, "p_form_car_rental_m.phid_pc")

    useBeforeClick(() => {
        const start_dt = mstform.getItem("u_start_dt").getValue()
        const end_dt = mstform.getItem("u_end_dt").getValue()
        if (!start_dt || !end_dt) {
            $NG.alert("表头 开始日期 或 结束日期 为空！")
            return false
        }
    }, 'addrow')

    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_car_rental_d")

    function StartIsEndDate(start, end) {
        if (start && end) {
            const startT = new Date(start).getTime()
            const endT = new Date(end).getTime()
            if (startT == endT) {
                return true
            }
            return startT > endT
        }
        return true
    }

    function sumAmt() {
        const _arr = dgrid.getRows();
        const fromStartDate = mstform.getItem("u_start_dt").getValue();
        const fromEndDate = mstform.getItem("u_end_dt").getValue();

        // 汇总金额
        let _count = 0
        _arr.forEach(item => {
            const m_start_dt = mstform.getItem("u_start_dt").getValue()
            const m_end_dt = mstform.getItem("u_end_dt").getValue()
            if (!StartIsEndDate(item.u_start_dt, m_start_dt)) {
                item.u_start_dt = null
                $NG.alert("明细开始时间不能早于表头开始时间")
            }
            if (!StartIsEndDate(m_end_dt, item.u_end_dt)) {
                item.u_end_dt = null
                $NG.alert("明细结束不能晚于表头结束时间")
            }
            if (!item.u_start_dt) {
                item.u_start_dt = fromStartDate;
            }
            if (!item.u_end_dt) {
                item.u_end_dt = fromEndDate;
            }
            item.u_zlyf = dateSubtraction(item.u_end_dt, item.u_start_dt);
            //申请含税金额
            item.u_vat_amt = (Number(item.u_zlyf) || 0) * (Number(item.u_yz_vat_amt) || 0);
            item.amt = (Number(item.u_vat_amt) || 0) * (1 - Number(item.taxrate))
            item.u_taxamount = Number(item.u_vat_amt) - Number(item.amt);

            _count += Number(item.u_vat_amt) || 0
            if (!item.taxrate && item.taxrate != 0) {
                item.taxrate = 0
            }


        })
        if (window.__cache_lsz?._count !== _count) {
            if (!window.__cache_lsz) {
                window.__cache_lsz = {}
            }
            window.__cache_lsz = _count
            $NG.updateState((updater) => {
                updater.data.p_form_car_rental_m.setProps({
                    u_cnt_amt: _count
                })
            })
        }
        kzCode()
        dgrid.refreshView();
    }


    useDataIndexChange(({ args }) => {
        getFynameByFyno(args[0].u_cost_pcno, (data) => {
            args[0].u_cost_pcname = data.u_name
            dgrid.refreshView()
        })
    }, "u_cost_pcno")


    useValuesChange(({ args }) => {
        setDataDgrid()
    }, "p_form_car_rental_m.u_start_dt")

    useValuesChange(({ args }) => {
        setDataDgrid()
    }, "p_form_car_rental_m.u_end_dt")

    useDataIndexChange(({ args }) => {
        dgridEditDate(args[0])
    }, "u_start_dt")
    useDataIndexChange(({ args }) => {
        dgridEditDate(args[0])
    }, "u_end_dt")

    // const _sum_key=[
    //     "u_zlyf",
    //     "u_yz_vat_amt",
    //     "u_vat_amt",
    //     "amt",
    //     "taxrate",
    //     "u_taxamount",
    //     "u_start_dt",
    //     "u_end_dt",
    // ]
    // _sum_key.forEach((item) => {
    // 	useDataIndexChange(({ args }) => {
    // 		const _arr = args[0];
    // 		//申请含税金额
    // 		_arr.u_vat_amt =
    // 			(Number(_arr.u_zlyf) || 0) * (Number(_arr.u_yz_vat_amt) || 0);
    // 		_arr.amt =
    // 			(Number(_arr.u_vat_amt) || 0) * (1-Number(_arr.taxrate))
    // 		_arr.u_taxamount = Number(_arr.u_vat_amt) - Number(_arr.amt);
    //     dgrid.refreshView()
    // 	}, item);
    // });


    // 控制费用选择 和 时间隐藏
    page.oType != 'view' && kzCode()
    function kzCode() {
        console.log(`开始过滤`,);
        window._catch_fycode = null
        const grid = dgrid
        try {
            grid.getRows().forEach((item) => {
                if (item.u_cost_pc) {
                    window._catch_fycode = {
                        u_cost_pc: item.u_cost_pc,
                        u_cost_pc_EXName: item.u_cost_pc_EXName
                    }
                    throw "终止forEach"
                }
            })
        } catch (e) { }
        if (window._catch_fycode) {
            console.log(`单一过滤`, "phid = " + window._catch_fycode.u_cost_pc);
            $NG.updateUI((updater) =>
                updater.editGrid.p_form_car_rental_d.u_cost_pc.setProps((p) => {
                    return {
                        ...p,
                        editor: {
                            ...p.editor,
                            clientSqlFilter: "phid = " + window._catch_fycode.u_cost_pc
                        },
                    };
                })
            );
        } else {
            $NG.updateUI((updater) =>
                updater.editGrid.p_form_car_rental_d.u_cost_pc.setProps((p) => {
                    return {
                        ...p,
                        editor: {
                            ...p.editor,
                            clientSqlFilter: ("phid in('8570000000000352','8570000000000382')")
                        },
                    };
                })
            );
        }

        // 时间隐藏
        const len = grid.getRows().length
        let disabled = false
        if (len == 0) {
            disabled = false
        } else {
            disabled = true
        }
        console.log(`disable`, disabled);
        $NG.updateUI((updater) =>
            updater.fieldSetForm.p_form_car_rental_m.u_start_dt.setProps({
                disabled: disabled
            }));
        $NG.updateUI((updater) =>
            updater.fieldSetForm.p_form_car_rental_m.u_end_dt.setProps({
                disabled: disabled
            }));
    }

    //表体日期编辑
    function dgridEditDate(el) {
        el.u_zlyf = dateSubtraction(el.u_end_dt, el.u_start_dt)
        dgrid.refreshView()
    }

    // 日期监听逻辑
    function setDataDgrid() {
        const _arr = dgrid.getRows();
        const fromStartDate = mstform.getItem("u_start_dt").getValue();
        const fromEndDate = mstform.getItem("u_end_dt").getValue();
        // 日期赋值
        _arr.forEach((item) => {
            item.u_start_dt = fromStartDate;
            item.u_end_dt = fromEndDate;
            item.u_zlyf = dateSubtraction(item.u_end_dt, item.u_start_dt);
        });
        dgrid.refreshView();
    }

    // 过滤费用项目
    fyxmFilter()
    function fyxmFilter() {
        $NG.updateUI((updater) =>
            updater.editGrid.p_form_car_rental_d.u_cost_pc.setProps((p) => {
                return {
                    ...p,
                    editor: {
                        ...p.editor,
                        clientSqlFilter: ("phid in('8570000000000352','8570000000000382')")
                    },
                };
            })
        );
    }
    // 项目信息获取
    getProjectInfo();
    function getProjectInfo(
        isReturn = false,
        phid = mstform.getItem("phid_pc").getValue(),
        fun
    ) {
        if (!mstform.getItem("phid_pc").getValue()) return;
        try {
            setTimeout(() => {
                $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
                    const _data = JSON.parse(res.data)[0].extendObjects;
                    if (res.count == 0) return;
                    console.log(`获取项目信息`, _data);
                    if (isReturn) {
                        fun(_data);
                    } else {
                        $NG.updateState((updater) => {
                            updater.data.p_form_car_rental_m.setProps({
                                u_pc_no: _data.pc_no, //项目编码
                                u_fycdgs: {
                                    //事业部or组织
                                    value: _data.cwhszz,
                                    label: _data.cwzz_name,
                                },
                                u_jzgs: {
                                    //事业部or组织
                                    value: _data.org_phid,
                                    label: _data.org_name,
                                },
                                //项目经理
                                phid_emp: {
                                    label: _data.project_manager_name,
                                    value: _data.project_manager_phid,
                                },
                                u_sqgw: {
                                    //售前顾问
                                    value: _data.user_sqgw_phid,
                                    label: _data.user_sqgw_name,
                                },
                                u_regional_center: {
                                    //区域中心
                                    value: _data.regional_center_phid,
                                    label: _data.regional_center_name,
                                },
                                u_product_line: {
                                    //产品线
                                    value: _data.midwife_phid,
                                    label: _data.midwife_name,
                                },
                                u_fycdbm: {
                                    //部门
                                    value: _data.org_phid,
                                    label: _data.org_name,
                                },
                                u_pc_type: {
                                    //项目类型
                                    value: _data.type_phid,
                                    label: _data.type_name,
                                },
                            });
                        });
                    }
                });
            }, 100);
        } catch (err) {
            $NG.alert("获取项目信息发生失败请检查~");
        }
    }
    // 根据费用编码获取费用名称
    function getFynameByFyno(phid, fun) {
        $NG.execServer("getFynameByFyno", { phid }, function (res) {
            console.log(res);
            if (res.count == 0 || !phid) return
            const _data = JSON.parse(res.data)[0].extendObjects
            fun(_data)
        })
    }
    //月数计算
    function dateSubtraction(date1, date2) {
        const d1 = new Date(date1);
        const d2 = new Date(date2);

        if (isNaN(d1.getTime()) || isNaN(d2.getTime())) {
            return null;
        }

        const timeDiff = Math.abs(d1 - d2);
        const daysDiff = timeDiff / (1000 * 60 * 60 * 24);
        return (daysDiff / 30).toFixed(2)
    }
});

